#！ /bin/bash

echo -e "network:\n    ethernets:\n        [device]:\n            addresses: [192.168.[net].[ip]/24]\n            [gateway]\n            nameservers:\n                addresses: [192.168.[net].1,202.96.128.166,202.96.134.133,8.8.8.8]\n            dhcp4: no\n    version: 2">50-cloud-init.yaml

echo -n "请输入网段:"
read ips
sed -i 's/\[net\]/'$ips'/g' 50-cloud-init.yaml
set ipf=1

#check if ip is occupied
set index=1
while [[ $index -eq 0 ]] #数值后面要加空格，双框号
do
    echo -n "请输入IP尾段:"
    read ipf
   
    set checkip=192.168.$ips.$ipf
    if ping -q $checkip -c 5
    then
        echo "IP 已被占用"
        index=0
    else
        echo "IP 可用"
        index=1
    fi
done

#建立文件
touch 50-cloud-init.yaml



sed -i 's/\[ip\]/'$ipf'/g' 50-cloud-init.yaml
str22gateway="routes:\n                - to: default\n                  via: 192.168."$ips".1"  #yaml文件看空格数，最好不要用tab
str20gateway="gateway4: 192.168."$ips".1"
gateway=" "
if lsb_release -a|grep 22 
then
    gateway=$str22gateway
else
    gateway=$str20gateway
fi
sed -i 's/\[gateway\]/'"$gateway"'/g' 50-cloud-init.yaml

if  nmcli d|grep ethernet
then
    echo "使用network manager请输入设备序号:"
    read num
    devicename=`nmcli d|grep ethernet|awk 'NR=="'$num'"{print $1}'`
    sed -i 's/\[device\]/'$devicename'/g' 50-cloud-init.yaml
    sudo cp 50-cloud-init.yaml /etc/netplan/
    
else
    ip addr |grep ': <'
    echo "使用ip address请输入设备序号:"
    read num
    devicename=`ip addr |grep ': <'|awk 'NR=="'$num'"{print $2}'`
    sed -i 's/\[device\]:/'$devicename'/g' 50-cloud-init.yaml
    cp 50-cloud-init.yaml 01-netcfg.yaml
    sudo cp 01-netcfg.yaml /etc/netplan/
fi
# 配置系统

sudo netplan apply